import React from "react";
import "./less/login.less";
import logoImg from "../assets/logo.png";
import { Form, Input, Button, Spin, message } from "antd";
import { Link } from "react-router-dom";
import { login } from "../network/api";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
export default function Login() {
  let [isLoading, setLoading] = useState(false);
  let navigate = useNavigate();
  const onFinish = async (values) => {
    isLoading = setLoading(true);
    try {
      const result = await login(values);
      localStorage.setItem("userinfo", JSON.stringify(result.data));
      message.success(result.message);
      navigate("/list");
    } catch (error) {
      console.log("error: ", error);
    }
    isLoading = setLoading(false);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className="login-wrapper">
      <Spin tip="Loading..." spinning={isLoading}>
        <div className="login-box">
          <img src={logoImg} alt="" />
          <Form
            name="basic"
            initialValues={{
              remember: true,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: "请输入用户名!",
                },
              ]}
            >
              <Input placeholder="请输入用户名" size="large" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请输入密码!",
                },
              ]}
            >
              <Input.Password placeholder="请输入密码" size="large" />
            </Form.Item>
            <Form.Item>
              <Link to="/register">还没账号？立即注册</Link>
            </Form.Item>

            <Form.Item>
              <Button type="primary" block size="large" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Spin>
    </div>
  );
}
